<?php
require_once(dirname(dirname(__FILE__)) . '/app.php');


$orderId = $_GET['id'];
//Logs::setLog("sdfsjfdlksjdfkdsfjlsdjflk");
if( $orderId > 0 ){
	$order = Preengage::GetById($orderId);
	$defaultShopId = $order['shop_id'];
	$serviceId = $order['service_id'];
	$staffId = $order['designation_stuff'];
	$deviceId = $order["device_id"];
	
	if( $oauthMap[10] == null){
		exit;
	}
	
}else{
	$order = Preengage::GetById($orderId);
	
	$defaultShopId = 1;
	$shop = Shop::getById($defaultShopId);
	$serviceId = 0;
	$staffId = 0;
	$deviceId = 0;
	
	if( $oauthMap[13] == null){
		exit;
	}
}

$shopList = Shop::GetAllShops();

$serviceList = Service::GetAllByShopId($defaultShopId);
$deviceList = Devices::GetAllByShopId($defaultShopId);
$staffList = Staff::GetAllByShop($defaultShopId);


$searchDate = $_REQUEST['start_date'];
$getDateArray = array();

if( preg_match("#/#", $searchDate) ){
	$getDateArray = explode("/", $searchDate);
}else if( preg_match("#-#", $searchDate) ){
	$getDateArray = explode("-", $searchDate);
}else{
	array_push($getDateArray, substr($searchDate, 0, 4));
	array_push($getDateArray, substr($searchDate, 4, 2));
	array_push($getDateArray, substr($searchDate, 6, 2));
}

$year = $getDateArray[0] * 1;
$month = $getDateArray[1] * 1;
$getTimeArray = explode(" ", $getDateArray[2]);
$day = $getTimeArray[0] * 1;
$getTimeArray = explode(":", $getTimeArray[1]);
$startHour = $getTimeArray[0];
$startMinute = $getTimeArray[1];


$tmp_date=date("Ymd");
$year = $year > 0 ? $year : substr($tmp_date,0,4) * 1;
$month = $month > 0 ? $month : substr($tmp_date,4,2) * 1;
$day = $day > 0 ? $day : substr($tmp_date, 6, 2) * 1;
if( is_post() ){
	$backupOrder = null;
	$serviceId = $_POST['service_id'];

	$deviceId = $_POST['device_id'];
	$staffId = $_POST['staff_id'];
	$deviceId = $_POST['device_id'];
	
	$endHour = $_POST['endHour'];
	$endMinute = $_POST['endMinute'];
	
	$hasAddBackUp = false;
	
	
	$orderId = $_POST['id'];
	$telNo = $_POST['tel_no'];
	$name = $_POST['name'];
	
	$order = Preengage::GetById($orderId);
	
//	if( $orderId > 0 ){
//		$year = date("y", $order['service_start_time']);
//		$month = date("m", $order['service_start_time']);
//		$day = date("d", $order['service_start_time']);
//	}
	
	$service = Service::GetById($serviceId);
	$shop = Shop::getById($defaultShopId);
	if($endHour < 1){
		$endMinute = $startMinute + $service['service_duration'];
		$endHour = $startHour;
		while ($endMinute > 59){
			$endMinute = $endMinute - 60;
			$endHour = $endHour + 1;
		}
	}
	$result = true;
	if( $startHour < $shop['open_hour'] || $endHour > $shop['close_hour'] ){
		Logs::setLog('sfdsdf.1111||'.$shop['open_hour'] + "||".$shop['close_hour']."||".$startHour."||".$endHour);
		$result = false;
	}else if( ($startHour == $shop['open_hour'] && $startMinute < $shop['open_minute']) || 
		($endHour == $shop['close_hour'] && $endMinute > $shop['close_minute']) ){
		Logs::setLog('予約時間不正');
		Session::Set('error', '予約時間不正');
		$result = false;
	}
	if( $result ){
		if( $orderId > 0 ){
			$backupOrder = Preengage::GetById($orderId);
			Preengage::DeleteById($orderId);
		}
		
		$result = ShopOrderLimit::CanBook($defaultShopId, $service, $year, $month, $day, $startHour, $startMinute, $endHour, $endMinute);
		
	}
	
	//Logs::setLog("haha result = $result");
	if( $result == 1 ){
		$startTime = mktime($startHour, $startMinute, 0, $month, $day, $year);
		$endTime = mktime($endHour, $endMinute, 0, $month, $day, $year);
		
		if( $staffId < 1 ){
			
			for($index = 1; $index < 5; $index++){
				$staffIds = StaffSkill::GetStaffsBySkillAndLevle($serviceId, $index);
				foreach( $staffIds as $k => $v ){
					$tempStaff = Staff::getById( $v['staff_id'] );
					if( $tempStaff['activity'] == Staff::$FLAG_UNACTIVE ){
						continue;
					}
					
					$temp = WorkSchedule::HasWork($startTime, $endTime, $v['staff_id']);
					if( $temp == null ){
						continue;
					}
					$temp = Preengage::HasOrdered($startTime - $service['reset_device_time'], $endTime, $v['staff_id']);
					if($temp != null){
						continue;
					}
					
					$temp = Absence::HasAbsence($startTime, $endTime, $v['staff_id']);
					if($temp != null){
						continue;
					}
					
					$staffId = $v['staff_id'];
					break;
				}
				if( $staffId > 0 ){
					break;
				}
			}
		}else{
			$temp = Preengage::HasOrdered($startTime - $service['reset_device_time'], $endTime, $staffId);
			if( $temp != null ){
				Logs::setLog("  =====11=======>".date("y-m-d H:i", $startTime));
			}
			
			$temp1 = StaffSkill::GetByStaffAndSkill($staffId, $serviceId);
			
			if( $temp1 == null ){
				Logs::setLog("  =====11=======>".date("y-m-d H:i", $startTime)."|| $serviceId || $staffId");
			}
			if($temp != null || $temp1 == null){
				Session::Set('error', 'ご指名スタッフはこの時間で予約取れませんの為に、ご予約できませんでした。');
				if( $backupOrder != null && !$hasAddBackUp){
					Preengage::CreateByBackUp($backupOrder);
					$hasAddBackUp = true;
				}
				include template('service/edit_succ');
				exit;
			}
		}
		
		
		if($deviceId < 1){
			$orderedCount = Preengage::GetOrderedCount($defaultShopId, $serviceId, $year, $month, $day, $startHour, $startMinute, $endHour, $endMinute);
			$orderedCount = $orderedCount[0];
			for($index = 1; $index < 5; $index++){
				$deviceIds = DeviceUse::GetDevicesBySkillAndLevel($serviceId, $index);
				foreach( $deviceIds as $k => $v ){
					$temp = Devices::GetById($v['device_id']);
					Logs::setLog("  orderedCount = ".$orderedCount['count']."  ||".$temp['device_count']);
					if( $temp['device_count'] <= $orderedCount['count'] ){
						continue;
					}
					$deviceId = $v['device_id'];
					break;
				}
				if( $deviceId > 0 ){
					break;
				}
			}
			
		}
		
	if( $staffId < 1 ){
			//Logs::setLog(" zui shi hua  kaishi ");
			$otherOrderStaff = ShopOrderLimit::GetOtherOrderStaff($serviceId, $startTime, $endTime);
			
			foreach ($otherOrderStaff as $k => $v){
				//Logs::setLog(" zui shi hua  kaishi 1 ".$v['staff_id']);
				if( $staffId > 0 ){
					break;
				}
				
				$temp = StaffSkill::GetByStaffAndSkill($v['staff_id'], $serviceId);
				if( $temp == null ){
					continue;
				}
				
				$temp = Absence::HasAbsence($startTime, $endTime, $v['staff_id']);
				if( $temp != null ){
					continue;
				}
				
				$temp = Preengage::HasOrderedSuchService($startTime, $endTime, $v['staff_id'], $serviceId);
				//Logs::setLog(" zui shi hua  kaishi 1<$serviceId> 2 ".$v['staff_id']);
				if( $temp != null ){
					continue;
				}
				//Logs::setLog(" zui shi hua  kaishi 1<$serviceId> 3 ".$v['staff_id']);
				$temp = Preengage::HasOrdered($startTime, $endTime, $v['staff_id']);
				//Logs::setLog(" zui shi hua  kaishi 1<$serviceId> 4 ".$v['staff_id']);
				$replaceAble = true;
				$replaceAbleStaffId = array();
				foreach($temp as $k1 => $v1){
					Logs::setLog(" zui shi hua  kaishi 1<$serviceId> 5 ".$v1['id']);
					$tempStaffs = StaffSkill::GetStaffsBySkill( $v1['service_id'] );
					foreach($tempStaffs as $k2 => $v2){
						if($v2['staff_id'] == $v1['designation_stuff']){
							continue;
						}
						
						$result = Utility::able2work($v2['staff_id'], $v1['service_start_time'], $v1['real_end_time']);
						//Logs::setLog(" zui shi hua  kaishi 1<$serviceId> 6 ".$v2['staff_id']);
						if( !$result || $v2['staff_id'] == $v1['designation_stuff']){
							continue;
						}
						//Logs::setLog(" zui shi hua  kaishi 1<$serviceId> 7 ".$v2['staff_id']);
						$replaceAbleStaffId[$k1] = $v2['staff_id'];
						break;
					}
					//Logs::setLog(" zui shi hua  kaishi 1<$serviceId> 8 ".$v2['staff_id']);
					if($replaceAbleStaffId[$k1] < 1){
						//Logs::setLog(" zui shi hua  kaishi 1<$serviceId> 9 ".$v2['staff_id']);
						$replaceAble = false;
						break;
					}
				}
				
				if( $replaceAble ){
					foreach($temp as $k1 => $v1){
						$v1['designation_stuff'] = 	$replaceAbleStaffId[$k1];	
						Preengage::UpdateByOrige($v1);
					}
					$staffId = $v['staff_id'];
				}
				
			}
			
			//その時間にその店員は働いているか
			$temp = Preengage::HasOrdered($startTime, $endTime + $service['reset_device_time'], $staffId);
			//できるやつがいるか
			$temp1 = StaffSkill::GetByStaffAndSkill($staffId, $serviceId);
			if($temp != null || $temp1 == null){
				Session::Set('error', '大変申し訳ございません。お客様ご予約したい時間帯は込み合っている為に予約取れませんでした。');
				include template('preengage_succ');
				exit;
			}
			
		
		}
		
		
		if( $orderId < 1 && $_POST['user_id'] > 0 ){
			//Logs::setLog("  add              sdl;fdskjfljlk");
			$order['user_id'] = $_POST['user_id'];
		}
		
		//if( $orderId < 1 ){
		if( $staffId < 1 || $deviceId < 1 ){
			Logs::setLog("  =====11=======> ||$staffId,,,||$deviceId ");
			Session::Set('error', '大変申し訳ございませんでした。お客様ご予約したい時間帯は込み合っている為に予約取れませんでした。');
			if( $backupOrder != null && !$hasAddBackUp){
					Preengage::CreateByBackUp($backupOrder);
					$hasAddBackUp = true;
				}
		}else{
			$staff = Staff::getById($staffId);
			Logs::setLog(" opuid = $login_user_id  || $backupOrder");
			if( $telNo == null || $telNo == "" ){
				Logs::setLog(" 111opuid = $login_user_id  || $backupOrder");
				
				Utility::sendMail($staff, $backupOrder, null);
				Preengage::Create($order['user_id'], $serviceId, $defaultShopId, $startTime, $endTime, $service['service_price'], $staffId, $deviceId, $_POST['isDesignationed'] == 1, 1, $login_user_id, $backupOrder);
			}else{
				Logs::setLog(" 22opuid = $login_user_id  || $backupOrder");
				Utility::sendMail($staff, null, null);
				Preengage::Create(0, $serviceId, $defaultShopId, $startTime, $endTime, $service['service_price'], $staffId, $deviceId, $_POST['isDesignationed'] == 1, 1, $login_user_id, $backupOrder, $telNo, $name);

			}
			Session::Set('msg', '予約完了しました。');
			include template('service/edit_succ');
			exit;
		}
		/*}else{
			Preengage::Update($orderId, $order['user_id'], $serviceId, $defaultShopId, $startTime, $endTime, $service['service_price'], $staffId, $deviceId);
		}*/
		
	}else{
		if( $backupOrder != null && !$hasAddBackUp){
			Preengage::CreateByBackUp($backupOrder);
			$hasAddBackUp = true;
		}
		Logs::setLog("225予約上限になりましたので、予約できません。<$year, $month, $day, $startHour, $startMinute, $endHour, $endMinute>");
		Session::Set('error', '予約上限になりましたので、予約できません。');
	}
	if( $backupOrder != null && !$hasAddBackUp){
		Preengage::CreateByBackUp($backupOrder);
		$hasAddBackUp = true;
	}
	include template('service/edit_succ');
	exit;
}
include template('/service/edit_order');
//include template('subscribe');
